import Vue from "vue";
import Vuex from "vuex";
import { fetchGoodsList } from "@/api";

Vue.use(Vuex);

export default new Vuex.Store({
  // 定义
  state: {
    shopList: [],
    num: 3,
    shopListObj: {},
    selectedFood: null,
  },
  // 获取状态
  getters: {
    //通过id获取商品
    getFoodById: (state) => (categoryId, foodId) => {
      const category = state.shopListObj[categoryId];
      if (category && category.foods) {
        return category.foods.find((food) => food.id === foodId);
      }
      return null;
    },
    //获取所有选中商品
    selectedItems(state) {
      const items = [];
      for (const categoryId in state.shopListObj) {
        const category = state.shopListObj[categoryId];
        if (category && category.foods) {
          category.foods.forEach((food) => {
            if (food.count > 0) {
              items.push({
                categoryId: categoryId,
                id: food.id,
                name: food.name,
                price: food.price,
                count: food.count,
              });
            }
          });
        }
      }
      return items;
    },
    //总数
    totalSelectedCount(state) {
      let total = 0;
      for (const categoryId in state.shopListObj) {
        const category = state.shopListObj[categoryId];
        if (category && category.foods) {
          category.foods.forEach((food) => {
            if (food.count > 0) {
              total += food.count;
            }
          });
        }
      }
      return total;
    },
    //总价
    totalPrice(state) {
      let total = 0;
      for (const categoryId in state.shopListObj) {
        const category = state.shopListObj[categoryId];
        if (category && category.foods) {
          category.foods.forEach((food) => {
            if (food.count > 0) {
              total += food.price * food.count;
            }
          });
        }
      }
      return total;
    },
  },
  // 同步
  mutations: {
    setSelectedFood(state, { categoryId, foodId }) {
      const food = state.shopListObj[categoryId]?.foods.find(
        (food) => food.id === foodId
      );
      state.selectedFood = food;
    },
    clearCart(state) {
      for (const categoryId in state.shopListObj) {
        const category = state.shopListObj[categoryId];
        if (category && category.foods) {
          category.foods.forEach((food) => {
            Vue.set(food, "count", 0); // 使用 Vue.set 确保响应性
          });
          Vue.set(category, "count", 0); // 更新分类的总数
        }
      }
    },
    //添加的方法
    add(state, { categoryId, foodId }) {
      const category = state.shopListObj[categoryId];
      if (category && category.foods) {
        const food = category.foods.find((food) => food.id === foodId);
        if (food) {
          food.count += 1;
          // 重新计算分类的总数
          category.count = category.foods.reduce(
            (total, food) => total + food.count,
            0
          );
        }
      }
    },
    //删除的方法
    decrement(state, { categoryId, foodId }) {
      const category = state.shopListObj[categoryId];
      if (category && category.foods) {
        const food = category.foods.find((food) => food.id === foodId);
        if (food && food.count > 0) {
          food.count -= 1;
          // 重新计算分类的总数
          category.count = category.foods.reduce(
            (total, food) => total + food.count,
            0
          );
        }
      }
    },
    setShopListObj(state, payload) {
      state.shopListObj = payload;
    },
  },
  // 异步
  actions: {
    //获取商品列表并进行处理
    FetchGoodsList({ commit }) {
      if (this.state.shopListObj[0]) {
        return this.state.shopListObj;
      } else {
        return fetchGoodsList()
          .then((res) => {
            const shopListWithCount = res.goodsList.map((item) => {
              // 为 item 对象添加 count 属性，值为 1
              // 同时，如果 item 中有 food 数组，也为 food 数组中的每个对象添加 count 属性
              const updatedFoods = item.foods
                ? item.foods.map((foodItem) => ({
                    ...foodItem,
                    count: 0,
                  }))
                : [];
              const categoryTotal = updatedFoods.reduce(
                (total, food) => total + food.count,
                0
              );
              return {
                ...item,
                count: categoryTotal,
                foods: updatedFoods, // 使用更新后的 food 数组
              };
            });
            commit("setShopListObj", shopListWithCount);
            return shopListWithCount;
          })
          .catch((error) => {
            console.error("请求失败", error);
            throw error;
          });
      }
    },
    clearCart({ commit }) {
      commit("clearCart");
    },
    setSelectedFood({ commit }, { categoryId, foodId }) {
      commit("setSelectedFood", { categoryId, foodId });
    },
  },
  modules: {},
});
